package com.swipemaster.network.task;

import java.util.ArrayList;

import android.app.Activity;
import android.widget.ListView;

import com.swipemaster.dialogs.Dialogs;
import com.swipemaster.dialogs.RecordsListAdapter;
import com.swipemaster.network.Network;
import com.swipemaster.network.WorldRecord;
import com.swipemaster.record.RecordId;

/** Asynchronous task for downloading more records (while already displaying level records dialog). */
public class DownloadMoreRecordsTask extends ProgressTask<Void, Void, ArrayList<WorldRecord>>
{
	private final RecordId recordId;
	private final ListView listView;
	private final RecordsListAdapter adapter;

	public DownloadMoreRecordsTask(Activity activity, ListView listView, RecordsListAdapter adapter, RecordId recordId)
	{
		super(activity);
		this.recordId = recordId;
		this.listView = listView;
		this.adapter = adapter;
	}

	@Override
	protected ArrayList<WorldRecord> doInBackground(Void... params)
	{
		try
		{
			return Network.getWorldRecords(recordId, adapter.getCount(), adapter.getStep());
		}
		catch (final Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	@Override
	protected void onPostExecute(ArrayList<WorldRecord> result)
	{
		super.onPostExecute(result);

		if (result == null)
		{
			Dialogs.showInternetError(activity);
			return;
		}

		adapter.addRecords(result);
		listView.invalidateViews();
		listView.setSelection(adapter.getCount());
	}
}